package etnorservice.etnor_service.controller;

import etnorservice.etnor_service.domain.ProblemDO;
import etnorservice.etnor_service.domain.po.FeedBack;
import etnorservice.etnor_service.domain.po.FeedbackDTO;
import etnorservice.etnor_service.domain.vo.TicktsVO;
import etnorservice.etnor_service.request.CancelProblemRequest;
import etnorservice.etnor_service.request.ProblemSearchRequest;
import etnorservice.etnor_service.request.ProblemSubmitRequest;
import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.EmailService;
import etnorservice.etnor_service.service.FeedbackService;
import etnorservice.etnor_service.service.ProblemService;
import etnorservice.etnor_service.service.UserService;
import etnorservice.etnor_service.utils.JwtTokenUtil;
import net.sf.jsqlparser.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/08/29/14:02
 **/
@RestController
public class ProblemSubmitController {
    @Autowired
    UserService userService;
    @Autowired
    ProblemService problemService;
    @Autowired
    FeedbackService feedbackService;
    @Autowired
    private EmailService emailService;  // 添加邮件服务依赖
    @GetMapping("/system/baseParms")
    public Result getBaseParms(){
        Result result = new Result();
        result.setData(problemService.getBaseParm());
        result.setCode(200);
        return result;
    }
    @PostMapping("/system/problemsubmit")
    public Result problemSubmit(
            @RequestBody ProblemSubmitRequest problemSubmitRequest,
            @RequestHeader(value = "Authorization", required = false)
                    String authorizationHeader){

        String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Integer id=Integer.parseInt(account);
        Integer talentId=userService.findRoleByAccount(id).getId();
        problemSubmitRequest.setTalentId(talentId);
        Result result = new Result();

        try {
            problemService.insertProblem(problemSubmitRequest);
            result.setMessage("成功");
            result.setCode(200);
        }catch (Exception e){
            result.setCode(400);
            result.setMessage("失败");
        }
        return result;
    }

    private String extractTokenFromHeader(String header) {
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        return header.substring(7).trim(); // 去除 "Bearer ".length() 后面的空格
    }

    @GetMapping("/system/getProblems")
    public Result getProblems(@RequestHeader(value = "Authorization", required = false)
                                          String authorizationHeader){
        Result result=new Result();
        String account=
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Integer id=Integer.parseInt(account);
        Integer talentId=userService.findRoleByAccount(id).getId();
        result.setData(problemService.problems(talentId));
        result.setCode(200);
        return result;
    }
    @PostMapping("/system/cancelProblem")
    public Result cancelProblem(@RequestBody CancelProblemRequest cancelProblemRequest){
        Result result=new Result();
        try {
            problemService.cancelProblem(cancelProblemRequest.getProblemid());
            result.setCode(200);
        }catch (Exception e){
            result.setCode(400);
        }
        return result;
    }
    //前台问题接受


    //返回前端问题类型
    @GetMapping("/problemList")
    public Result getProblemList(){
        Result result=new Result();
        result.setData(problemService.getProblemList());
        return result;
    }
    @PostMapping("/submitFeedback")
    public Result submitFeedback(  @RequestParam("problemType") String problemType,
                                   @RequestParam("summary") String summary,
                                   @RequestParam(value = "description", required = false) String description,
                                   @RequestParam("severity") String severity,
                                   @RequestParam("contact") String contact,
                                   @RequestParam("userId") Long userId,
                                   @RequestParam(value = "supportingFiles", required = false) MultipartFile supportingFiles){
        Result result=new Result();
        // 创建反馈对象
        FeedbackDTO feedback = new FeedbackDTO();
        feedback.setUserId(userId);
        feedback.setProblemType(problemType);
        feedback.setSummary(summary);
        feedback.setDescription(description);
        feedback.setSeverity(severity);
        feedback.setContact(contact);
        return feedbackService.submitFeedback(feedback);
    }


//page=1&pageSize=10&status=&priority=&search=


 @GetMapping("/system/tickets")
public Result getProblemList(
        @RequestParam String page,
        @RequestParam String pageSize,
        @RequestParam(required = false) String status,
        @RequestParam(required = false) String priority,
        @RequestParam(required = false) String startDate,  // 修改为单独的开始日期
        @RequestParam(required = false) String endDate,    // 修改为单独的结束日期
        @RequestParam(required = false) String search
) {
    // 创建 ProblemSearchRequest 对象
    ProblemSearchRequest request = new ProblemSearchRequest();

    // 设置参数
     request.setFinished(status.isEmpty()?null:status);
    request.setUrgency(priority.isEmpty()?null:priority);
    request.setKeyWords(search.isEmpty()?null:search);

    // 处理日期
    if (startDate != null && endDate != null) {
        request.setStartTime(parseDate(startDate));
        request.setEndTime(parseDate(endDate));
    }
     // 计算 limit 和 offset
        int pageNum = Integer.parseInt(page);
        int pageSizeNum = Integer.parseInt(pageSize);
        int offset = (pageNum - 1) * pageSizeNum;
        int limit = pageSizeNum;
        request.setLimit(limit);
        request.setOffset(offset);



    List<TicktsVO> problemDOList=problemService.findProblemsByConditions(request);

    // 调用服务层方法
    Result result = new Result();
    result.setData(problemDOList);
    result.setCode(200);

    return result;
}
    // 辅助方法：解析日期字符串
    private Date parseDate(String dateStr) {
        // 这里假设日期格式为 "yyyy-MM-dd"
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return dateFormat.parse(dateStr);
        } catch (java.text.ParseException e) {
            throw new RuntimeException("Invalid date format", e);
        }
    }
    @GetMapping("/system/feedback/list")
    public Result getFeedbackList(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(required = false) Integer status,
                                  @RequestParam(required = false) String keyword) {
        return feedbackService.getFeedbackList(page, pageSize, status, keyword);
    }


    @PostMapping("/system/feedback/handle")
    public Result handleFeedBack(@RequestParam Integer state, @RequestParam Long problemId) {
        Result result = new Result();
        try {
            // 获取反馈详情
            FeedbackDTO feedback = feedbackService.getFeedbackById(problemId);
            if (feedback != null && feedback.getContact() != null) {
                // 更新状态
                feedbackService.updateFeedbackStatus(problemId, state);

                // 准备邮件变量
                Map<String, Object> templateVariables = new HashMap<>();
                templateVariables.put("feedbackId", feedback.getId());
                templateVariables.put("summary", feedback.getSummary());
                templateVariables.put("statusName", getStatusName(state));

                // 发送邮件通知
                String subject = "问题反馈状态更新：" + feedback.getSummary();
                emailService.sendStatusUpdateEmail(feedback.getContact(), subject, templateVariables);

                result.setCode(200);
                result.setMessage("状态更新成功");
            } else {
                result.setCode(200);
                result.setMessage("状态更新成功，但未发送邮件通知");
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("处理失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 添加回复接口
    @PostMapping("/system/feedback/reply")
    public Result replyFeedback(@RequestParam Long problemId,
                                @RequestParam String content,
                                @RequestParam(required = false) String email) {
        Result result = new Result();
        try {
            // 获取反馈详情
            FeedbackDTO feedback = feedbackService.getFeedbackById(problemId);
            if (feedback != null) {
                // 保存回复内容（如需实现）
                // feedbackService.saveFeedbackReply(problemId, content);

                // 准备邮件变量
                String contactEmail = email != null && !email.isEmpty() ? email : feedback.getContact();
                if (contactEmail != null && !contactEmail.isEmpty()) {
                    Map<String, Object> templateVariables = new HashMap<>();
                    templateVariables.put("feedbackId", feedback.getId());
                    templateVariables.put("summary", feedback.getSummary());
                    templateVariables.put("replyContent", content);

                    // 发送邮件通知
                    String subject = "您的反馈已收到回复：" + feedback.getSummary();
                    emailService.sendReplyEmail(contactEmail, subject, templateVariables);
                }

                result.setCode(200);
                result.setMessage("回复发送成功");
            } else {
                result.setCode(404);
                result.setMessage("反馈不存在");
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("回复失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 辅助方法：获取状态名称
    private String getStatusName(Integer status) {
        switch(status) {
            case 0: return "待处理";
            case 1: return "处理中";
            case 2: return "已完成";
            case 3: return "已关闭";
            default: return "未知状态";
        }
    }

    @PostMapping("/system/promotion/send-material")
    public Result sendPromotionMaterial(@RequestBody Map<String, String> request) {
        Result result = new Result();
        String email = request.get("email");

        if (email == null || email.isEmpty()) {
            result.setCode(400);
            result.setMessage("邮箱地址不能为空");
            return result;
        }

        try {
            // 发送宣传邮件
            String subject = "欢迎了解ETNOR-API接口管理平台";
            emailService.sendPromotionEmail(email, subject);

            result.setCode(200);
            result.setMessage("宣传资料已成功发送到您的邮箱");

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("发送失败，请稍后再试: " + e.getMessage());

        }

        return result;
    }
}
